package com.itheima.controller;


import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.CheckItem;
import com.itheima.service.CheckItemService;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.swing.*;
import java.util.List;

@RestController
@RequestMapping("/checkitem")
public class CheckItemController {

    @Reference
    public CheckItemService checkItemService;

    //新增检查项
    @PostMapping("/add")
    public Result insertCheckItem(@RequestBody CheckItem checkItem) {
        //参数校验
        if (checkItem == null || StringUtils.isEmpty(checkItem.getName())
                || StringUtils.isEmpty(checkItem.getCode())) {
            return new Result(false, MessageConstant.ADD_CHECKITEM_FAIL);
        }
        try {
            Integer integer = checkItemService.insertCheckItem(checkItem);
            if (integer == 1) {
                return new Result(true, MessageConstant.ADD_CHECKITEM_SUCCESS);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Result(false, MessageConstant.ADD_CHECKITEM_FAIL);
    }

    //根据id删除检查项
    @PostMapping("/delete")
    public Result deleteCheckItem(@RequestBody Integer id) {
        try {
            Integer integer = checkItemService.deleteCheckItem(id);
            if (integer == 1) {
                return new Result(true, MessageConstant.DELETE_CHECKITEM_SUCCESS);
            } else if (integer == -1) {
                return new Result(false, "检查项被检查组绑定，无法删除！");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Result(false, MessageConstant.DELETE_CHECKITEM_FAIL);
    }


    /**
     * 根据id或编码或名称进行查询
     *
     * @param queryPageBean
     * @return
     */
    @PostMapping("/findPage")
    public PageResult findByAll(@RequestBody QueryPageBean queryPageBean) {

        final PageResult pageResult = checkItemService.findByAll(queryPageBean);
        if (null == pageResult) {
            return null;
        }
        return pageResult;
    }

    /**
     * 根据检查组获取检查项内容
     */
    @GetMapping("/findAll")
    public Result findAll() {
        final List<CheckItem> all = checkItemService.findAll();
        return new Result(true,MessageConstant.QUERY_CHECKGROUP_SUCCESS,all);
    }
}
